package cn.ug.msg.web.controller;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.enums.ThirdSourceEnum;
import cn.ug.enums.WxTemplateEnum;
import cn.ug.feign.MemberThirdService;
import cn.ug.member.bean.response.MemberThirdFindBean;
import cn.ug.msg.mq.WxMessageParamBean;
import cn.ug.msg.service.WxMessageNoticeService;
import cn.ug.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 微信通知
 */
@RestController
@RequestMapping("wxNotice")
public class WxMessageNoticeController extends BaseController {

    @Autowired
    private WxMessageNoticeService wxMessageNoticeService;

    @Autowired
    private MemberThirdService memberThirdService;

    /**
     * 消息发送
     */
    @RequestMapping(value = "send", method = POST)
    public SerializeObject send(WxMessageParamBean entity) {
        if (entity.getType() == null) {
            return new SerializeObject(ResultType.NORMAL, "类型不能为空");
        }
        WxTemplateEnum wxTemplateEnum = WxTemplateEnum.getWxTemplateByCode(entity.getType());
        if (wxTemplateEnum == null) {
            return new SerializeObject(ResultType.NORMAL, "类型不匹配");
        }

        if (StringUtils.isBlank(entity.getOpenid())) {
            SerializeObject<MemberThirdFindBean> serializeObject = memberThirdService.find(null, entity.getMemberId(), ThirdSourceEnum.WXACCOUNT.getType());
            if (serializeObject.getData() != null)
                entity.setOpenid(serializeObject.getData().getOpenId());
        } else if (!StringUtils.isBlank(entity.getOpenid())) {
            SerializeObject<MemberThirdFindBean> serializeObject = memberThirdService.find(entity.getOpenid(), null, ThirdSourceEnum.WXACCOUNT.getType());
            if (serializeObject.getData() == null) {
                return new SerializeObject(ResultType.UNAUTH, "该用户尚未绑定微信公众号");
            }
        }

        if (!StringUtils.isBlank(entity.getOpenid())) {
            entity.setTemplateId(wxTemplateEnum.getTemplateId());
            return wxMessageNoticeService.sendNotice(entity);
        }
        return new SerializeObject(ResultType.UNAUTH, "该用户尚未注册微信公众号");
    }
}
